# -*- coding: utf-8 -*-
# @Date   : 2020/3/19
# @File   : R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_2D_CF2.py
# @Author : zhaochen
'''eof
name:申请人近6个月内贷记卡累计逾期次数校验
code:R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_2D_CF2
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
import pandas as pd
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def getCount(statusList, min, max, endMonth=None, type=1, deltaMonth=6):
    if statusList in null_type_list:
        return -1
    if type == 1:
        stateStr = 'PD01DD01'  # 24个月还款状态
        monthStr = 'PD01DR03'  # 月份
    else:
        stateStr = 'PD01ED01'  # 五年的还款状态
        monthStr = 'PD01ER03'  # 月份
    if endMonth is None:
        # 使用当前时间为阈值
        endMonthStr = datetime.datetime.now().strftime("%Y-%m-%d")
        endMonthFact = float(endMonthStr[:4]) * 12 + float(endMonthStr[5:7])
    else:
        try:
            # 使用传入的截止日期计算阈值
            endMonthFact = float(endMonth[:4]) * 12 + float(endMonth[5:7]) if len(endMonth) >= 6 else None
            if endMonthFact is None:
                return -1
        except:
            return -1
    monthsAgo = endMonthFact - deltaMonth
    result = [0] # 返回数字的state的list
    flag = False
    for i in statusList:
        try:
            state = i.get(stateStr)
            month = i.get(monthStr)
            monthFact = float(month[:4]) * 12 + float(month[5:7])
            if state not in null_type_list:
                flag = True
            if ((isfloat(state) and min <= int(state) <= max)) and  monthFact > monthsAgo:
                # 存值
                result.append(int(state)-min+1)
        except:
            continue
    if flag:
        return result
    else:
        return -1

def checkNull(data, accountType):
    '''若最近24个月还款状态信息为空，返回结果为缺失值，则进行以下逻辑判断：
1.基本信息段（PD01A）-账户类型（PD01AD01）为D1，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为5（转出）且转出月份（PD01BR04）＞5年，则Factor=1,否则Factor=缺失值；
2.基本信息段（PD01A）-账户类型（PD01AD01）为R1,R4，若最新表现信息段（PD01B）-账户状态（PD01BD01）为3（结清）且关闭日期（PD01BR01）＞5年，则Factor=1,否则Factor=缺失值；
3.基本信息段（PD01A）-账户类型（PD01AD01）为R2，R3，若最新表现信息段（PD01B）-账户状态（PD01BD01）为4(销户)且关闭日期（PD01BR01）＞5年或账户状态（PD01BD01）为6(未激活)，则Factor=1,否则Factor=缺失值；'''
    if data in null_type_list or data == [{}] or data == 0:
        return 0
    # 账户状态
    PD01BD01 = data[0].get("PD01BD01")
    # 关闭日期
    PD01BR01 = data[0].get("PD01BR01")
    PD01BR01 = dateFormat(PD01BR01)
    # 转出月份
    PD01BR04 = data[0].get("PD01BR04")
    PD01BR04 = dateFormat(PD01BR04)
    fiveYearsAgo = datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=5)
    if accountType == "D1":
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01 < fiveYearsAgo)\
                or (PD01BD01 == "5" and PD01BR04 is not None and PD01BR04 < fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R1", "R4"]:
        if (PD01BD01 == "3" and PD01BR01 is not None and PD01BR01 < fiveYearsAgo):
            return 1
        else:
            return 0
    elif accountType in ["R2", "R3"]:
        if (PD01BD01 == "4" and PD01BR01 is not None and PD01BR01 < fiveYearsAgo) \
                or (PD01BD01 == "6"):
            return 1
        else:
            return 0
    else:
        return 0

def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_2D_CF2():
    data = IC_DSJ_2D['data']
    # 借贷账户信息
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            factor = []
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                    else:
                        # 账号类型
                        PD01AD01 = PD01A[0].get("PD01AD01")
                        if PD01AD01 not in null_type_list:
                            if PD01AD01 in ['R2']:
                                # 最近24个月还款状态信息段 PD01D[0.1]
                                PD01D = getTable(i, 'PD01D', 0, 1)
                                if not (PD01D == [{}] or PD01D == 0):
                                    PD01D = PD01D[0]
                                    # 获取24位状态码列表
                                    PD01DH = PD01D.get("PD01DH")
                                    # 24个月的截止日期
                                    PD01DR02 = PD01D.get("PD01DR02")
                                    stateList = getCount(PD01DH, min=1, max=7, endMonth=PD01DR02, type=1, deltaMonth=6)
                                    if stateList == -1:
                                        factor.append(None)
                                    else:
                                        # factor.extend(stateList)
                                        factor.append(len([i for i in stateList if i != 0]))
                                else:
                                    # 最新表现信息段  PD01B  [1..1]
                                    PD01B = getTable(i, 'PD01B', 1, 1)
                                    # 最近5年内的历史表现信息段
                                    PD01E = getTable(i, 'PD01E', 0, 1)
                                    if PD01E == [{}] or PD01B == [{}]:
                                        factor.append(None)
                                    elif PD01E == 0:
                                        factor.append(0)
                                    else:
                                        # 截止年月：
                                        PD01ER02 = PD01E[0].get('PD01ER02')
                                        # 历史表现信息 PD01EH
                                        PD01EH = PD01E[0].get('PD01EH')
                                        # 账户状态
                                        PD01BD01 = PD01B[0].get('PD01BD01')
                                        if PD01BD01 in null_type_list:
                                            factor.append(None)
                                        else:
                                            if PD01BD01 in ['1', '2']:
                                                # 未结清使用截止日期判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=PD01ER02, type=2,
                                                                     deltaMonth=6)
                                            else:
                                                # 已结清使用当前时间判断
                                                stateList = getCount(PD01EH, min=1, max=7, endMonth=None, type=2,
                                                                     deltaMonth=6)
                                            if stateList == -1:
                                                # 检查是否为5年之外结清或者转出的情况
                                                checkRes = checkNull(PD01B, accountType=PD01AD01)
                                                if checkRes:
                                                    factor.append(0)
                                                else:
                                                    factor.append(None)
                                            else:
                                                factor.append(len([i for i in stateList if i != 0]))

                            else:
                                factor.append(0)
                        else:
                            factor.append(None)
                except:
                    factor.append(None)
                    continue

    factorNotNone = filter(lambda x: x is not None, factor)
    if len(factorNotNone) == 0:
        return u'缺失值'
    else:
        return max(factorNotNone)

result = R16_IC_AccOvduCntOfLoansAndCreditAndQuasiSixMonsCheck_2D_CF2()